import React from 'react';
import './../../form.less';

import moment from 'moment';
import {Button, Col, Icon, Input, message, Popconfirm, Row, Tooltip} from 'antd';
import BreadcrumbCustom from "../../../common/BreadcrumbCustom";
import BannerTable from "./BannerTable";
import BannerCreateForm from "./BannerForm";

export default class Banner extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pageSize: 5,
            total: 0,
            current: 1,
            linkUrl: '',
            visible: false, //新建窗口隐藏
            dataSource: [],
            selectedRowKeys: [],
            isUpdate: false,
            loading: true,
        };
    }

    //用户名输入
    onChangeLinkUrl = (e) => {
        const value = e.target.value;
        this.setState({
            linkUrl: value,
        })
    };

    pageSizeChange = (current, pageSize) => {
        console.log(pageSize + " "+current)
        this.setState({
            pageSize: pageSize,
            current: current
        },() => this.getData())
    }

    getData = () => {
        var url = '/manage/banner/query'
        const searchCondiction = new Object()
        searchCondiction.pageSize = this.state.pageSize;
        searchCondiction.pageNumber = this.state.current;
        console.log("pageSize" + this.state.pageSize)
        console.log("pageNumber" + this.state.current)
        if (this.state.linkUrl) {
            const conditionList = [];
            const condition = {
                code: "linkUrl",
                type: "String",
                operator: 1,
                value: this.state.linkUrl
            }
            conditionList.push(condition);
            searchCondiction.conditionList = conditionList;
        }
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(searchCondiction)
        }).then((response) => {
            return response.json()
        }).then((res) => {
            console.log(res)
            if (res.code == 200) {
                this.setState({
                    datasource: res.result.list,
                    total:res.result.total,
                    loading: false
                });
            }
        })
    }

    //渲染
    componentDidMount() {
        this.getData();
    }

    //搜索按钮
    btnSearch_Click = () => {
        this.getData();
    };
    //重置按钮
    btnClear_Click = () => {
        this.setState({
            linkUrl: ''
        });
    };
    //新建信息弹窗
    CreateItem = () => {
        this.setState({
            visible: true,
            isUpdate: false,
        });
        const form = this.form;
        form.resetFields();
    };
    //新增
    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);
            values.createtime = moment().format("YYYY-MM-DD hh:mm:ss");
            var url = '/manage/banner/save'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code == 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                }
            })
            form.resetFields();
            this.setState({
                visible: false,
            });
        });
    };
    //更新修改
    handleUpdate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);
            var url = '/manage/banner/update'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code == 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                }
            })
            form.resetFields();
            this.setState({
                visible: false,
            });
        });
    };
    //取消
    handleCancel = () => {
        this.setState({visible: false});
    };
    //批量删除
    MinusClick = () => {
        this.state.selectedRowKeys.forEach(index => {
            this.onDelete(this.state.datasource[index].id)
        })
    };
    //单个删除
    onDelete = (bannerId) => {
        console.log(bannerId)
        var url = '/manage/banner/' + bannerId;
        fetch(url, {
            method: 'DELETE'
        }).then((response) => {
            return response.json()
        }).then((res) => {
            if (res.code == 200) {
                message.success("操作成功")
                this.getData();
            } else {
                message.success("操作失败")
            }
        })
    };
    //点击修改
    editClick = (key) => {
        const banner = this.state.datasource.filter(banner => banner.id == key)[0];
        const form = this.form;
        form.setFieldsValue({
            id:banner.id,
            linkUrl:banner.linkUrl,
            picUrl:banner.picUrl
        });
        this.setState({
            visible: true,
            isUpdate: true,
        });
    };
    //单选框改变选择
    checkChange = (selectedRowKeys) => {
        this.setState({selectedRowKeys: selectedRowKeys});
    };

    render() {
        const questiontxt = () => {
            return (
                <p><Icon type="plus-circle-o"/> : 新建Banner<br/>
                    <Icon type="minus-circle-o"/> : 批量删除</p>
            )
        };
        return (
            <div>
                <BreadcrumbCustom paths={['首页', 'Banner管理']}/>
                <div className='formBody'>
                    <Row gutter={16}>
                        <Col className="gutter-row" sm={8}>
                            <Input
                                placeholder="跳转地址"
                                value={this.state.linkUrl}
                                onChange={this.onChangeLinkUrl}
                            />
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <div className='plus' onClick={this.CreateItem}>
                            <Icon type="plus-circle"/>
                        </div>
                        <div className='minus'>
                            <Popconfirm title="确定要批量删除吗?" onConfirm={this.MinusClick}>
                                <Icon type="minus-circle"/>
                            </Popconfirm>
                        </div>
                        <div className='question'>
                            <Tooltip placement="right" title={questiontxt}>
                                <Icon type="question-circle"/>
                            </Tooltip>
                        </div>
                        <div className='btnOpera'>
                            <Button type="primary" onClick={this.btnSearch_Click}
                                    style={{marginRight: '10px'}}>查询</Button>
                            <Button type="primary" onClick={this.btnClear_Click}
                                    style={{background: '#f8f8f8', color: '#108ee9'}}>重置</Button>
                        </div>
                    </Row>
                    <BannerTable
                        dataSource={this.state.datasource}
                        checkChange={this.checkChange}
                        onDelete={this.onDelete}
                        editClick={this.editClick}
                        loading={this.loading}
                        pageSizeChange={this.pageSizeChange}
                        total={this.state.total}
                        pageSize={this.state.pageSize}
                        current={this.state.current}
                    />
                    {this.state.isUpdate ?
                        <BannerCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                          onCancel={this.handleCancel} onCreate={this.handleUpdate} title="修改Banner"
                                          okText="更新"/>
                        : <BannerCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                            onCancel={this.handleCancel} onCreate={this.handleCreate} title="新建Banner"
                                            okText="保存"/>}
                </div>
            </div>
        )
    }
}